package com.rp.news.util;


import com.github.pagehelper.PageInfo;
import com.rp.news.common.NewsCommon;
import com.rp.news.common.PagedResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class CommonUtil {

    @Value("${website.domain-name:rpnews.com}")
    private String domainName;

    public PagedResult setterPageResult(List<?> list, Integer page) {
        PageInfo<?> pageInfo = new PageInfo<>(list);
        PagedResult result = new PagedResult();
        result.setPage(page);
        result.setTotal(pageInfo.getPages());
        result.setRecords(pageInfo.getTotal());
        result.setRows(list);
        return result;
    }


    public Map<String, String> getErrors(BindingResult bindResult) {
        Map<String, String> map = new HashMap<>();
        List<FieldError> fieldErrors = bindResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return map;
    }

    public void setCookie(HttpServletRequest request,
                          HttpServletResponse response,
                          String cookieName, String cookieValue, Integer maxAge) {

        String encode = null;
        try {
            encode = URLEncoder.encode(cookieValue, "UTF-8");
            setCookieValue(request, response, cookieName, maxAge, encode);
        } catch (UnsupportedEncodingException e) {
            log.info("=============setCookie============");
            e.printStackTrace();
        }

    }

    private void setCookieValue(HttpServletRequest request,
                                HttpServletResponse response, String cookieName, Integer maxAge, String encode) {
        Cookie cookie = new Cookie(cookieName, encode);
        cookie.setDomain(domainName);
        cookie.setMaxAge(maxAge);
        cookie.setPath("/");
        response.addCookie(cookie);

    }

    public void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
        String encode = null;
        try {
            encode = URLEncoder.encode("", "utf-8");
            setCookie(request, response, cookieName, encode, NewsCommon.COOKIE_DELETE);
        } catch (UnsupportedEncodingException e) {
            log.info("=============deleteCookie============");
            e.printStackTrace();
        }
    }
}
